<template>
    <!-- 角色管理页面根容器 -->
    <div class="role-container">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">
                    <el-icon class="title-icon">
                        <Key />
                    </el-icon>
                    角色管理
                </h1>
                <p class="page-description">管理系统角色配置，包括角色的增删改查操作</p>
            </div>
        </div>

        <!-- 主要内容卡片 -->
        <el-card class="main-card" shadow="hover">
            <!-- 搜索和操作区域 -->
            <div class="action-section">
                <!-- 内联表单用于搜索 -->
                <el-form :inline="true" :model="QueryInfo" class="search-form">
                    <el-form-item label="角色名称" class="form-item">
                        <el-input v-model="QueryInfo.RoleName" placeholder="请输入角色名称" clearable class="search-input" />
                    </el-form-item>
                    <el-form-item class="form-item">
                        <el-button type="primary" @click="roleinfo" class="action-btn search-btn"
                            icon="el-icon-search">查询</el-button>
                        <el-button type="success" @click="addPopup" class="action-btn add-btn"
                            icon="el-icon-plus">角色新增</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 数据表格 -->
            <div class="table-section">
                <el-table :data="tableData" style="width: 100%" border class="data-table" stripe highlight-current-row>
                    <el-table-column type="index" label="编号" width="80" align="center" />
                    <el-table-column prop="RoleName" label="角色名称" width="120" align="center" />
                    <el-table-column prop="PermissionName" label="权限" width="250" align="center" />
                    <el-table-column prop="status" label="是否启用" width="100" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.status ? 'success' : 'info'">
                                {{ scope.row.status ? '启用' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Serialnumber" label="序号" width="100" align="center" />
                    <el-table-column prop="CreateTime" label="创建时间" width="160" align="center">
                        <template #default="scope">
                            <!-- 使用moment.js格式化时间 -->
                            {{ moment(scope.row.CreateTime).format('YYYY-MM-DD HH:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="140" align="center">
                        <template #default="scope">
                            <div class="action-buttons">
                                <el-button link type="danger" size="small" @click="deleteRole(scope.row)"
                                    class="delete-btn" icon="el-icon-delete">删除</el-button>
                                <el-button link type="primary" size="small" @click="editRole(scope.row)"
                                    class="edit-btn" icon="el-icon-edit">修改</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页组件 -->
            <div style="margin-top: 16px; display: flex; justify-content: center;">
                <div class="pagination-section">
                    <table>
                        <tr>
                            <td>
                                <el-pagination v-model:current-page="QueryInfo.PageIndex"
                                    v-model:page-size="QueryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,sizes" :total="QueryInfo.TotalCount" @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                                    共{{ QueryInfo.TotalCount }}条 每页{{ QueryInfo.PageSize }}条
                                    第{{ QueryInfo.PageIndex }}/{{ QueryInfo.TotalPage }}页
                                </el-pagination>
                            </td>
                            <td>
                                <el-pagination v-model:current-page="QueryInfo.PageIndex"
                                    v-model:page-size="QueryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,prev, pager, next" :total="QueryInfo.TotalCount"
                                    @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                    prev-text="上一页" next-text="下一页">
                                    <el-button @click="handleCurrentChange(1)"
                                        :disabled="QueryInfo.PageIndex == 1">首页</el-button>
                                </el-pagination>
                            </td>
                            <td>
                                <el-pagination v-model:current-page="QueryInfo.PageIndex"
                                    v-model:page-size="QueryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,jumper" :total="QueryInfo.TotalCount" @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                                    <el-button @click="handleCurrentChange(QueryInfo.TotalPage)"
                                        :disabled="QueryInfo.PageIndex == QueryInfo.TotalPage">首页</el-button>
                                </el-pagination>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

        </el-card>

        <!-- 角色新增弹窗 -->
        <el-dialog v-model="dialogFormVisible" title="添加角色" width="600px" class="custom-dialog"
            :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="form" :rules="rules" ref="addFormRef" label-width="100px" class="dialog-form">
                    <el-form-item label="角色名称" prop="RoleName">
                        <el-input v-model="form.RoleName" placeholder="请输入角色名称" clearable />
                    </el-form-item>
                    <el-form-item label="序号" prop="Serialnumber">
                        <el-input-number v-model="form.Serialnumber" :min="1" placeholder="请输入序号" style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="选择权限">
                        <el-checkbox-group v-model="form.PermissionId" class="permission-checkbox-group">
                            <el-checkbox v-for="item in perissoninfo" :key="item.PermissionsId"
                                :label="item.PermissionsId">
                                {{ item.PermissionName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="addSubmit" class="confirm-btn">确认提交</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改角色弹窗 -->
        <el-dialog v-model="editDialogVisible" title="修改角色" width="500px" class="custom-dialog"
            :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px" class="dialog-form">
                    <el-form-item label="角色名称" prop="RoleName">
                        <el-input v-model="editForm.RoleName" placeholder="请输入角色名称" clearable />
                    </el-form-item>
                    <el-form-item label="序号" prop="Serialnumber">
                        <el-input-number v-model="editForm.Serialnumber" :min="1" placeholder="请输入序号"
                            style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="选择权限">
                        <el-checkbox-group v-model="editPermissionId" class="permission-checkbox-group">
                            <el-checkbox v-for="item in perissoninfo" :key="item.PermissionsId"
                                :label="item.PermissionsId">
                                {{ item.PermissionName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="updateRole" class="confirm-btn">确认修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
// 导入所需模块
import { serviceRead, serviceWrite } from '@/utils/axionrequest';
import axios from 'axios';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import moment from 'moment';
import { onMounted, reactive, ref } from 'vue';



// 控制弹窗显示/隐藏的响应式变量
const dialogTableVisibleUpdate = ref(false)
const dialogFormVisible = ref(false)
const editDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
    RoleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
    Serialnumber: [
        { required: true, message: '请输入序号', trigger: 'blur' },
    ],
})

// 新增角色表单数据
const form = reactive({
    RoleName: '',
    Serialnumber: '',
    PermissionId: []
})

// 点击新增按钮，显示弹窗并清空表单数据
const addPopup = () => {
    dialogFormVisible.value = true;
    form.RoleName = ''
    form.Serialnumber = ''
    form.PermissionId = []
}


// 提交新增角色表单
const addSubmit = async () => {
    if (!addFormRef.value) return
    await addFormRef.value.validate((valid) => {
        if (valid) {
            serviceWrite.post('/api/Role/AddRole', form).then(res => {
                if (res.data.code == 200) {
                    ElMessage({
                        message: res.data.msg,
                        type: 'success',
                    })
                    dialogFormVisible.value = false; // 关闭弹窗
                    roleinfo(); // 刷新表格数据
                } else {
                    ElMessage.error(res.data.msg)
                }
            })
        }
    })
}

// 查询条件及分页参数
const QueryInfo = reactive({
    PageIndex: 1,
    PageSize: 5,
    RoleName: '',
    TotalCount: 0,
    TotalPage: 0
})

// 表格数据
const tableData = ref()

// 获取角色列表数据
const roleinfo = () => {
    serviceRead.get('/api/Roles/SraechRole', { params: QueryInfo }).then(res => {
        tableData.value = res.data.PageData
        QueryInfo.TotalCount = res.data.TotalCount
        QueryInfo.TotalPage = res.data.TotalPage
    })
}

// 权限数据，用于新增和修改时的权限选择
const perissoninfo = ref()

// 获取所有权限数据
const infodata = () => {
    serviceWrite.get('/api/Permissions/SreachPermissions').then(res => {
        // 确保权限ID为数字类型，以兼容el-checkbox-group
        perissoninfo.value = res.data.data.map((item: any) => ({
            ...item,
            PermissionsId: Number(item.PermissionsId)
        }))
    })
}

// 组件挂载时，初始化数据
onMounted(() => {
    roleinfo()
    infodata()
})

// 分页：每页显示条数变化
const handleSizeChange = (val: number) => {
    QueryInfo.PageSize = val
    roleinfo()
}
// 分页：当前页码变化
const handleCurrentChange = (val: number) => {
    QueryInfo.PageIndex = val
    roleinfo()
}

// 删除角色
const deleteRole = (row: any) => {
    ElMessageBox.confirm(
        '是否删除当前信息',
        '角色删除管理',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        serviceWrite.delete('/api/Role/DeleRole', { data: { RolesId: row.RolesId } }).then(res => {
            if (res.data.code === 200) {
                ElMessage.success(res.data.msg)
                roleinfo() // 刷新表格
            } else {
                ElMessage.error(res.data.msg)
            }
        }).catch(err => {
            ElMessage.error('删除失败: ' + (err.response?.data?.msg || err.message))
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除已取消',
        })
    })
}

// 修改角色表单数据
const editForm = reactive({
    RolesId: '',
    RoleName: '',
    status: true,
    Serialnumber: '',
    CreateTime: '',
    IsDeleted: false
})
// 用于修改时绑定权限ID
const editPermissionId = ref<number[]>([])

// 点击修改按钮，打开弹窗并回显数据
const editRole = (row: any) => {
    // 使用Object.assign或扩展运算符进行浅拷贝，避免直接修改表格数据
    Object.assign(editForm, row)

    // 反填权限ID，确保为数字数组
    let ids: number[] = []
    if (Array.isArray(row.PermissionId)) {
        ids = row.PermissionId.map((id: any) => Number(String(id).trim()))
    } else if (typeof row.PermissionId === 'string') {
        ids = row.PermissionId.split(',').map((id: string) => Number(id.trim())).filter((id: number) => !isNaN(id))
    } else if (row.PermissionId) {
        ids = [Number(String(row.PermissionId).trim())]
    }

    // 过滤出有效的权限ID
    const validIds = perissoninfo.value
        ? ids.filter(id => perissoninfo.value.some((item: any) => item.PermissionsId === id))
        : ids
    editPermissionId.value = validIds

    editDialogVisible.value = true
}

// 提交修改
const updateRole = async () => {
    if (!editFormRef.value) return
    await editFormRef.value.validate((valid) => {
        if (valid) {
            serviceWrite.put('/api/Role/UpdateRole', {
                ...editForm,
                PermissionId: editPermissionId.value // 将权限ID数组一并提交
            }).then(res => {
                if (res.data.code === 200) {
                    ElMessage.success(res.data.msg)
                    editDialogVisible.value = false // 关闭弹窗
                    roleinfo() // 刷新表格
                } else {
                    ElMessage.error(res.data.msg)
                }
            }).catch(err => {
                ElMessage.error('修改失败: ' + (err.response?.data?.msg || err.message))
            })
        }
    })
}
</script>

<style scoped>
.role-container {
    min-height: 100%;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    padding: 0;
}

.page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 32px 0;
    margin-bottom: 24px;
    border-radius: 0 0 16px 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.header-content {
    text-align: center;
    color: white;
}

.page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 8px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

.title-icon {
    font-size: 36px;
    color: #ffd700;
}

.page-description {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
}

.main-card {
    border-radius: 16px;
    border: none;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    background: rgba(255, 255, 255, 0.95);
}

.action-section {
    padding: 24px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    margin-bottom: 24px;
}

.search-form {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

.form-item {
    margin-bottom: 0;
}

.search-input {
    width: 300px;
}

.action-btn {
    border-radius: 8px;
    font-weight: 500;
    padding: 10px 20px;
    transition: all 0.3s ease;
}

.search-btn {
    background: linear-gradient(45deg, #409EFF, #67C23A);
    border: none;
}

.search-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.add-btn {
    background: linear-gradient(45deg, #67C23A, #E6A23C);
    border: none;
}

.add-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.table-section {
    padding: 0 24px 24px;
}

.data-table {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.edit-btn {
    color: #409EFF;
    font-weight: 500;
}

.edit-btn:hover {
    background: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
}

.delete-btn {
    color: #F56C6C;
    font-weight: 500;
}

.delete-btn:hover {
    background: rgba(245, 108, 108, 0.1);
    border-radius: 4px;
}

.custom-dialog {
    border-radius: 16px;
}

.dialog-content {
    padding: 20px 0;
}

.dialog-form {
    max-width: 100%;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
}

.cancel-btn {
    border-radius: 8px;
    padding: 10px 20px;
}

.confirm-btn {
    border-radius: 8px;
    padding: 10px 20px;
    background: linear-gradient(45deg, #409EFF, #67C23A);
    border: none;
}

.confirm-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 选择权限卡片美化 */
:deep(.permission-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(2, 130px);
  gap: 18px 100px;
  justify-content: center;
}
:deep(.permission-checkbox-group .el-checkbox) {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.06);
  margin-bottom: 0;
  min-width: 0;
  max-width: 180px;
  width: 100%;
  min-height: 48px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 16px;
  padding-left: 18px;
  padding-right: 18px;
  border: 1.5px solid #e4e7ed;
  transition: all 0.2s;
}
:deep(.permission-checkbox-group .el-checkbox.is-checked) {
  border-color: #409EFF !important;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.12);
  color: #222 !important;
  background: #f0f7ff;
}

.pagination-section {
    margin: 24px 0 0 0;
    text-align: right;
}

/* 调整弹框宽度 */
:deep(.el-dialog) {
    width: 600px !important;
    max-width: 90vw;
}
</style>